package com.itheima.user.dao.impl;

import com.itheima.user.dao.IUserDao;
import com.itheima.domain.User;


import java.io.*;
import java.util.ArrayList;

public class UserDaoImpl implements IUserDao {
    public static ArrayList<User> list = new ArrayList<>();

    @Override
    public void addUser(User user) {
        list.add(user);
    }

    @Override
    public void deleteUser(String username) {
        int index = getIndex(username);
        list.remove(index);
    }

    @Override
    public void updatePassword(String username, User user) {
        int index = getIndex(username);
        list.set(index, user);
    }

    @Override
    public ArrayList<User> findAllUser() {
        return list;
    }

    @Override
    public int getIndex(String username) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getUsername().equals(username)) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public void write() throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("system\\message\\User.txt"));
        oos.writeObject(list);
        oos.close();
    }

    @Override
    public void read() throws IOException, ClassNotFoundException {
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("system\\message\\User.txt"));
            list = (ArrayList<User>) ois.readObject();
        } catch (Exception e) {
        } finally {
            if (ois != null) {
                ois.close();
            }
        }
    }
}
